package event

import (
	"context"
	"ez/apps/tool/service"
	"ez/apps/wms/auto/mc"
	"ez/apps/wms/conf"
	wms "ez/apps/wms/document"
	"ez/apps/wms/services"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/tools"
)

func init() {
	ez.Subscribe(mc.InLogEventAfterSave, func(v interface{}, ctx context.Context) {
		md, ok := v.(*wms.InLog)
		if ok {
			if md.NumLeft == 0 && md.NumIn > 0 && !md.IsCanceled && md.NumOut == 0 {
				md.NumLeft = md.NumIn
				md.NumInReal = md.NumIn
			}
			md.Type = new(wms.IOType)
			md.Type.Id = md.TypeId
			md.LoadType()
			//如果不填单号就自动创建
			if md.Sn == "" {
				//创建批次号
				sn := service.CreateSnByString(ez.ConfigService.AppId, "StoreInSn:[YY][MM][DD][DMAX[3]]", 1)
				md.Sn = sn[len("StoreInSn:"):]
			}
			//如果不填批次号就自动创建
			if md.BatchCode == "" {
				//创建批次号
				sn := service.CreateSnByString(ez.ConfigService.AppId, "StoreInBatch:[YY][MM][DD][DMAX[3]]", 1)
				ez.Debug(sn)
				md.BatchCode = sn[len("StoreInBatch:"):]
			}
			//如果不填堆号就自动创建
			if md.HeapCode == "" {
				//创建批次号
				sn := service.CreateSnByString(ez.ConfigService.AppId, "StoreInHeap:[YY][MM][DD][DMAX[3]]", 1)
				md.HeapCode = sn[len("StoreInHeap:"):]
			}
			if md.Link == "" {
				md.Link = tools.CreateRandString(64)
			}
			//关于价格的计算暂未考虑进来
			//if md.BatchPrice == 0 {
			//	md.Cost = md.NumIn * md.BatchPrice
			//	md.CostReal = md.NumInReal * md.BatchPrice
			//}
			md.SetEvent(false)
			_ = md.Save()
			//更更新产品的库存
			itemSku, _ := wms.NewItemSkuCrud().FindId(md.ItemId)
			services.UpdateItemStorage(itemSku)
			services.CreateChangeLog(md.ItemId, conf.ChangeLogIn)
		} else {
			ez.Debug("断言失败")
		}
	})

}
